package com.gongj.loader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class MyLoader extends ClassLoader{

		public static final String SUFFIX = ".class";
		public static final int BUFFERSIZE = 1024;
		/**
		 *
		 * @param name: com.gongj.service.Test
		 * @return
		 * @throws ClassNotFoundException
		 */
		@Override
		protected Class<?> findClass(String name) throws ClassNotFoundException {
			System.out.println("==================自定义加载器开始=======");
			//加载D盘目录下指定类名的class
			String dir = "D:\\work\\service" + File.separatorChar + name.replace('.', File.separatorChar);
			byte[] classData = getData(dir);
			if (classData == null) {
				throw new ClassNotFoundException();
			} else {
				return defineClass(name, classData, 0, classData.length);
			}
		}

		private byte[] getData(String name) {
			File file = new File(name + SUFFIX);
			if (!file.exists()) {
				return null;
			}
			try(InputStream ins = new FileInputStream(file);
				ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
				int len = 0;
				byte[] buffer = new byte[BUFFERSIZE];
				while ((len = ins.read(buffer)) != -1) {
					bos.write(buffer, 0, len);
				}
				return bos.toByteArray();
			}catch (Exception e){
				e.printStackTrace();
			}
			return null;
		}

	}
